<?php
class Application_Model_Privilege {
	private $_id;
	private $_resourceId;
	private $_resourceType;
	private $_roleId;
	private $_roleType;
	private $_mode;

	public function setId($id) {
		$this->_id = $id;
	}

	public function setResourceId($id) {
		$this->_resourceId = $id;
	}

	public function setResourceType($type) {
		$this->_resourceType = $type;
	}

	public function setRoleId($id) {
		$this->_roleId = $id;
	}

	public function setRoleType($type) {
		$this->_roleType = $type;
	}

	public function setMode($mode) {
		$this->_mode = $mode;
	}

	public function getResource() {
		if($this->_resourceType == 'category') {
			return Application_Model_Category::findById($this->_resourceId);
		}
		else {
			return Application_Model_File::findById($this->_resourceId);
		}
	}

	public function getMode() {
		return $this->_mode;
	}

	public function getRole() {
		if($this->_roleType == 'user') {
			return Application_Model_User::findById($this->_roleId);
		}
		else {
			return Application_Model_Group::findById($this->_roleId);
		}
	}

	public static function findByCategories($categories) {
		$db = Zend_Db::factory ( 'Pdo_Mysql', array (
		'host' => 'localhost', 
		'username' => 'root', 
		'password' => '', 
		'dbname' => 'test' )
		 );

		$ids = array();
		foreach($categories as $category) {
			$ids[] = $category->getId();
		}

		$sql = 'SELECT id, resource_id, resource_type,
                               role_id, role_type, mode
                        FROM privileges
                        WHERE resource_type = "category"
                          AND resource_id IN(' . implode(', ', $ids) . ')';

		$rows = $db->fetchAssoc($sql);

		return self::_hydrateRows($rows);
	}

	public static function findByFile(File $file) {
		$db = Zend_Db::factory ( 'Pdo_Mysql', array (
		'host' => 'localhost', 
		'username' => 'root', 
		'password' => '', 
		'dbname' => 'test' )
		 );

		$sql = 'SELECT id, resource_id, resource_type,
                               role_id, role_type, mode
                        FROM privileges
                        WHERE resource_type = "file"
                          AND resource_id = ?';

		$rows = $db->fetchAssoc($sql, array($file->getId()));

		return self::_hydrateRows($rows);
	}

	public static function _hydrateRows($rows) {
		$results = array();

		foreach($rows as $row) {
			$privilege = new Application_Model_Privilege();
			$privilege->setId($row['id']);
			$privilege->setResourceId($row['resource_id']);
			$privilege->setResourceType($row['resource_type']);
			$privilege->setRoleId($row['role_id']);
			$privilege->setRoleType($row['role_type']);
			$privilege->setMode($row['mode']);
			$results[] = $privilege;
		}

		return $results;
	}
}